import 'package:common_utils/common_utils.dart';
import 'package:flukit/flukit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../message_model/em_message.dart';

class ChatWidgets {

  ///工具栏Widget-Swiper
  static Widget toolsSwiper(
      Map<String,dynamic> toolsData,
      {
        required List<Widget> toolsList,
        Function(String)? tap
      }){

    if (toolsList.isNotEmpty) {
      toolsList.clear();
    }

    List<Widget> widgets = [];
    toolsData.forEach((key, value){
      widgets.add(buildIcon(value, key,tap: (name){
        if(tap != null) {
          tap(name);
        }
      }));
    });

    toolsList.add(GridView.count(
        crossAxisCount: 4,
        padding: const EdgeInsets.all(0.0),
        children: widgets));

    return Swiper(
        autoStart: false,
        circular: false,
        indicator: CircleSwiperIndicator(
            radius: 3.0,
            padding: const EdgeInsets.only(top: 10.0, bottom: 10),
            itemColor: Colors.grey,
            itemActiveColor: Colors.red),
        children: toolsList);
  }

  ///聊天页面-工具栏item
  static Widget buildIcon(
      IconData icon,
      String? text,
      {
        Function(String)? tap
      }) {
    return Column(
      children: <Widget>[
        const SizedBox(
          height: 8,
        ),
        InkWell(
            onTap: () {
              if(tap != null) {
                tap(text??"");
              }
            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8.0),
              child: Container(
                width: 54,
                height: 54,
                color:  Colors.white,
                child: Icon(icon, size: 28,),
              ),
            )),
        const SizedBox(
          height: 5,
        ),
        Text(text!, style: const TextStyle(fontSize: 12),
        ),
      ],
    );
  }

  ///聊天页面-输入框
  static enterWidget({
    FocusNode? focusNode,
    TextEditingController? controller,
    ValueChanged<String>? onChanged,
    VoidCallback? onEditingComplete,
    double? textFieldHeight,
  }){
    return Material(
      borderRadius: BorderRadius.circular(19),
      shadowColor: Colors.black,
      color: Colors.white,
      elevation: 0,
      child: Container(
          height: textFieldHeight,
          constraints: const BoxConstraints(minHeight: 36, maxHeight: 400),
      child: TextField(
            focusNode: focusNode,
            textInputAction: TextInputAction.send,
            controller: controller,
            inputFormatters: [
              LengthLimitingTextInputFormatter(300), //长度限制11
            ], //只能输入整数
            style: const TextStyle(color: Colors.black, fontSize: 16),
            maxLines: 10,
            textAlignVertical: TextAlignVertical.center,
            decoration: const InputDecoration(
              contentPadding: EdgeInsets.only(left: 10,right: 0,top: 2),
              border: InputBorder.none,
              filled: true,
              fillColor: Colors.transparent,
              hintText: "请输入消息",
            ),
            onChanged: onChanged,
            onEditingComplete: (){
              if (controller!.text.isEmpty) {
                return;
              }
              if(onEditingComplete!=null){
                onEditingComplete();
              }
            }),
      ),
    );
  }


  ///聊天底部输入框Tab
  static Widget keyboardBar({
    double? bottomPadding,
    Widget? enterWidget,
    bool isShowSend = false,
    bool isShowTools = false,
    Function()? sendTap,
    Function()? showToolTap,
  }){
    return  Container(
      decoration:  const BoxDecoration(
        border: Border(top: BorderSide(width: 0.5, color: Color(0xFFE8E8E8)),
        ),
      ),
      child: Container(
        color: Colors.red,
        child: Padding(padding: EdgeInsets.only(bottom: bottomPadding??0,top: 9),
          child: Row(
            children: <Widget>[

              const Padding(padding: EdgeInsets.only(left: 15)),
              Expanded(child: enterWidget??Container()),
              const Padding(padding: EdgeInsets.only(right: 10)),
              isShowSend
                  ? InkWell(
                onTap: sendTap,
                child:  Container(
                  alignment: Alignment.center,
                  width: 40, height: 32,
                  margin: const EdgeInsets.only(right: 8),
                  decoration:  const BoxDecoration(
                    color: Colors.black,
                    borderRadius: BorderRadius.all(Radius.circular(8.0)),
                  ),
                  child:  const Text('发送', style: TextStyle(
                      fontSize: 14.0, color: Colors.white),
                  ),
                ),
              ) : InkWell(
                onTap: showToolTap,
                child: SizedBox(
                  width: 40,
                  child: Icon(isShowTools == true?Icons.keyboard_alt_outlined:Icons.add_circle_outline,size: 25,),
                )),

              const Padding(padding: EdgeInsets.only(right: 10)),
            ],
          ),
        ),
      ),
    );
  }

}










typedef OnItemClick = Future<void>? Function(Object); //控件点击时触发

class ChatItemWidgets {


  static Widget buildChatListItem(
      EMMessage? entity,
      EMMessage? nextEntity,
      {
        OnItemClick? onResend,
        OnItemClick? onItemClick,
      }) {
    bool isShowTime = true;
    var showTime; //最终显示的时间
    if (null == nextEntity) {
      isShowTime = true;
    } else {
      //如果当前消息的时间和上条消息的时间相差，大于3分钟，则要显示当前消息的时间，否则不显示
      if ((entity!.timestamp! - nextEntity.timestamp!).abs() >
          10 * 60 * 1000) {
        isShowTime = true;
      } else {
        isShowTime = false;
      }
    }
    showTime = TimelineUtil.format(entity!.timestamp!,locale:"zh",dayFormat: DayFormat.Full);

    return Column(
      children: <Widget>[
        isShowTime
            ? Center(
            child: Text(
              showTime,
              style: const TextStyle(color: ColorT.transparent_50),
            ))
            : const SizedBox(height: 0),


        _chatItemWidget(entity, onResend!, onItemClick!)
      ],
    );
  }

  static Widget _chatItemWidget(
      EMMessage entity, OnItemClick onResend, OnItemClick onItemClick) {
    if (entity.from == "") {
      //对方的消息
      return Container(
        margin: const EdgeInsets.only(left: 10, right: 90, bottom: 25, top: 4),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _headPortrait(type: "1"),
            const SizedBox(width: 10),
            Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    const Text(
                      "警网客服",
                      style: TextStyle(fontSize: 14, color: ColorT.gray_66),
                    ),
                    const SizedBox(height: 2),
                    GestureDetector(
                      child: _contentWidget(entity),
                      onTap: () {
                        onItemClick(entity);
                      },
                      onLongPress: () {
                        print("长按了消息");
                      },
                    ),
                  ],
                )),
          ],
        ),
      );
    } else {
      //自己的消息
      return Container(
        margin: const EdgeInsets.only(left: 90, right: 10, bottom: 25, top: 4),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: <Widget>[
                    GestureDetector(
                      child: _contentWidget(entity),
                      onTap: () {
                        onItemClick(entity);
                      },
                      onLongPress: () {
                        print("长按了消息");
                      },
                    ),
                  ],
                )),
            const SizedBox(width: 10),
            _headPortrait(type: "2"),
          ],
        ),
      );
    }
  }

  /*
  *  头像
  */
  static Widget _headPortrait({String type = "1"}) {
    return ClipRRect(
        borderRadius: BorderRadius.circular(18),
        child: Container(width: 36,height: 36,color:type == "1"? Colors.red:Colors.yellow,));
  }

  /*
  *  内容
  */

  static Widget _contentWidget(EMMessage entity) {
    Widget? widget;
    if (entity.ext?.weichat?.htmlSafeBody?.type == "txt"  || entity.body?.type == "txt") {
      widget = buildTextWidget(entity,content: entity.body?.text);
    }
    return widget ??Container();
  }

  static Widget buildTextWidget(EMMessage entity,{String? content}) {
    return Container(
      padding: const EdgeInsets.only(left: 10, right: 10, top: 8, bottom: 8),
      decoration: BoxDecoration(
        color: entity.from == "kefuchannelimid_632622"
            ? Colors.white
            : const Color(0xff4E81FF),
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(10),
          topRight:Radius.circular(2),
          bottomLeft: Radius.circular(10),
          bottomRight: Radius.circular(10),
        ),
      ),
      child:  Text(
        content??"",
        style: const TextStyle(fontSize: 16, color: Colors.black),
      ),
    );
  }

}


class ColorT {

  static const Color bg_color = Color(0xffF1F1F1);
  static const Color tool_color = Color(0xffEDEDED);
  static const Color transparent_80 = Color(0x80000000); //204
  static const Color transparent_50 = Color(0x50000000); //204

  static const Color text_dark = Color(0xFF333333);
  static const Color text_normal = Color(0xFF666666);
  static const Color text_gray = Color(0xFF999999);

  static const Color divider = Color(0xffe5e5e5);
  static const Color gray_33 = Color(0xFF333333); //51
  static const Color gray_66 = Color(0xFF666666); //102
  static const Color gray_99 = Color(0xFF999999); //153
}

